'use strict';
var WechatApi = require('co-wechat-api');
var moment=require('moment');
var CryptoJS = require('crypto-js');
var md5 = require('md5');
var sdk=require('tencentyoutuyun');
module.exports = app => {
  class shopredController extends app.Controller {
    async home() {
      var id=this.ctx.params.id;
      var activity=await this.ctx.model.Shopred.findById(id);
      var redData=await this.ctx.model.ShopredRed.findAll({where:{
          shopredId:id
      },
      });
      redData=JSON.parse(JSON.stringify(redData));

      var record=await this.ctx.model.ShopredRecord.findAll({where:{userId:this.ctx.session.user && this.ctx.session.user.id?this.ctx.session.user.id:375,shopredId:id}});
      for (var i=0;i<redData.length;i++){
          for(var p=0;p<record.length;p++){
              if(record[p].shopredRedId==redData[i].id){
                  record[p].imgRecord=JSON.parse(record[p].imgRecord);
                  var allCheck=true;
                  for (var o in record[p].imgRecord){
                      if(!record[p].imgRecord[o]){
                          allCheck=false;
                          break;
                      }
                  }
                  redData[i].allCheck=allCheck;
              }
          }
      }



      // this.ctx.body=redData;
      await this.ctx.render('shopred/index',{
          shopredId:id,
          redList:redData,
          user:this.ctx.session.user,
          jssdk:this.ctx.session.jssdk,
          wechat:this.ctx.session.wechat,
          activity:activity,
      });
    }
    * rule(){
        yield  this.ctx.render('shopred/rule',{
            wechat:this.ctx.session.wechat,
            user:this.ctx.session.user,
            jssdk:this.ctx.session.jssdk
        });
    }
    * detail(){



        // ctx.body=opencv;
        var shopredId=this.ctx.params.id;
      var redId=this.ctx.request.query.redId;
        var activity=yield this.ctx.model.Shopred.findById(shopredId);
      var imgList=yield this.ctx.model.ShopredImg.findAll({attributes:['id','imgurl'],where:{shopredRedId:redId}});
      var imgPass=yield this.ctx.model.ShopredRecord.findOne({attributes:['imgRecord'],where:{shopredRedId:redId,userId:this.ctx.session.user.id}});
      var img={url:'',num:''};
      if(imgPass && imgPass.imgRecord){
          imgPass.imgRecord=JSON.parse(imgPass.imgRecord);
          for(var i in imgPass.imgRecord){
              if(!imgPass.imgRecord[i]){
                  var thisimg=yield this.ctx.model.ShopredImg.findOne({attributes:['id','imgurl'],where:{id:parseInt(i)}});
                  img.url=thisimg.imgurl;
                  img.num=thisimg.id;
                  break;
              }
          }
          yield  this.ctx.render('shopred/detail',{
              shopredId:shopredId,
              redId:redId,
              img:img,
              wechat:this.ctx.session.wechat,
              user:this.ctx.session.user,
              jssdk:this.ctx.session.jssdk,
              activity:activity
          });
      }else{
          yield  this.ctx.render('shopred/detail',{
              shopredId:shopredId,
              redId:redId,
              img:{
                  url:imgList[0].imgurl,
                  num:imgList[0].id,
              },
              wechat:this.ctx.session.wechat,
              user:this.ctx.session.user,
              jssdk:this.ctx.session.jssdk,
              activity:activity
          });
      }


    }
    * result(ctx){
        var image1=ctx.request.body.image1;
        var image2=ctx.request.body.image2;
        console.log('原图：'+image1);
        console.log('上传：'+image2);
        const result1 =yield this.ctx.curl(image1);
        const result2 =yield this.ctx.curl(image2);
        var opencv=require('opencv/lib/opencv');

        var mat1= yield new Promise((resolve,reject)=>{
            opencv.readImage(result1.data, function(err, mat){
                resolve(mat);
            });
        });
        var mat2= yield new Promise((resolve,reject)=>{
            opencv.readImage(result2.data, function(err, mat){
                resolve(mat);
            });
        });
        var result;
        if((mat2.height()==0 && mat2.width()==0) || mat2.col().length<=0){
            result=false;
        }else {
            var similarityResult = yield new Promise((resolve, reject) => {
                opencv.ImageSimilarity(mat1, mat2, function(err, dissimilarity){
                    resolve({dissimilarity:dissimilarity});
                });
            });
            console.log(similarityResult);
            if(similarityResult.dissimilarity<=30){
                result=true;
            }else {
                result=false;
            }
        }


        // sdk.conf.setAppInfo('10098588', 'AKIDtc8QUK9KVR9duwdLirlRt78vUqyrH0C8', 'mIXWFhtoTt2vXtmRs41mJacOvDH6g5GD', '547437716', 0);
        // var result1 = yield new Promise((resolve, reject) => {
        //     sdk.youtu.imagetag(image1,　function (response) {
        //         resolve(response.data.tags);
        //     });
        // });
        // var result2 = yield new Promise((resolve, reject) => {
        //     sdk.youtu.imagetag(image2,　function (response) {
        //         resolve(response.data.tags);
        //     });
        // });
        // var keywordsNum=2;
        // if(result1.length<2 || result2.length<2){
        //     keywordsNum=1;
        // }
        // console.log(result1);
        // console.log(result2);
        // var keywords=0;
        // var result=false;
        // for(var i=0;i<result1.length;i++){
        //     for(var p=0;p<result2.length;p++){
        //         if(result1[i].tag_name==result2[p].tag_name && Math.abs(result1[i].tag_confidence-result2[p].tag_confidence)<=35){
        //             keywords++;
        //         }
        //     }
        // }
        // if(keywords>=keywordsNum){
        //     result=true;
        // }
        yield ctx.body={
          result:result
        };

    }
    * paydata(){
        function getRandom(probability){
            var probability = probability*100 || 1;
            var odds = Math.floor(Math.random()*100);

            if(probability === 100){return true};
            if(odds < probability){
                return true;
            }else{
                return false;
            }
        };
        function randomString(len) {
            len = len || 32;
            var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
            var maxPos = $chars.length;
            var pwd = '';
            for (var i = 0; i < len; i++) {
                pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
            }
            return pwd;
        };
        var user=yield this.ctx.model.User.findById(this.ctx.session.user.id);
        var redId=parseInt(this.ctx.request.body.redId);
        var shopredId=parseInt(this.ctx.request.body.shopredId);
        var uploadImg=this.ctx.request.body.uploadImg;
        var ip=this.ctx.request.body.ip;
        var num=parseInt(this.ctx.request.body.num);
        var red=yield this.ctx.model.ShopredRed.findById(redId);
        var acttivity=yield this.ctx.model.Shopred.findById(shopredId);
        var status=yield this.ctx.model.ShopredRecord.findOne({
            where:{
                shopredRedId:redId,
                userId:this.ctx.session.user.id,
            }
        });

        // var backIp=['219.128.232.249','219.128.234.101','117.136.41.17'];
        var backIp=yield this.ctx.model.Backip.findAll();
        var inBack=false;
        for(var i=0;i<backIp.length;i++){
            if(backIp[i].ip==ip.toString()){
                inBack=true;
                break;
            }
        }

        if(inBack){
            yield this.ctx.model.ShopredHistory.create({
                userId:this.ctx.session.user.id,
                shopredRedId:redId,
                amount:0,
                shopredImgId:num,
                ip:ip,
                uploadImg:uploadImg,
                remark:'黑名单ip地址'
            });
            this.ctx.body = {
                status:false,
                message:'寻在恶意行为，你已被加入广场黑名单！'
            };
        }else{
            if(parseInt(user.status)==1){
                yield this.ctx.model.ShopredHistory.create({
                    userId:this.ctx.session.user.id,
                    shopredRedId:redId,
                    amount:0,
                    shopredImgId:num,
                    ip:ip,
                    uploadImg:uploadImg,
                    remark:'恶意行为，加入黑名单'
                });
                this.ctx.body = {
                    status:false,
                    message:'寻在恶意行为，你已被加入广场黑名单！'
                };
            }else{
                if(status && status.imgRecord){
                    status.imgRecord=JSON.parse(status.imgRecord);
                }
                if(status && status.imgRecord[num]){//已经领过红包
                    this.ctx.body = {
                        status:true,
                        message:'你已领取过此红包，请勿重复领取！'
                    }
                }else{//还没领过此红包
                    var choujiang=getRandom(red.percent/100);
                    var user=yield this.ctx.model.ShopredRecord.findOne({
                        where:{
                            shopredRedId:redId,
                            userId:this.ctx.session.user.id,
                        }
                    });
                    if(user){//已经有记录
                        user.imgRecord=JSON.parse(user.imgRecord);
                        user.imgRecord[num]=true;
                        user.imgRecord=JSON.stringify(user.imgRecord);
                        yield this.ctx.model.ShopredRecord.update({
                            imgRecord:user.imgRecord
                        },{where:{
                            shopredRedId:redId,
                            userId:this.ctx.session.user.id,
                        }});
                    }else{
                        var imgList=yield this.ctx.model.ShopredImg.findAll({attributes:['id'],where:{shopredRedId:redId,}});
                        var pics={};

                        for(var i=0;i<imgList.length;i++){
                            pics[imgList[i].id]=false;
                        }
                        pics[num]=true;
                        pics=JSON.stringify(pics);
                        yield this.ctx.model.ShopredRecord.create({
                            shopredRedId:redId,
                            shopredId:shopredId,
                            userId:this.ctx.session.user.id,
                            imgRecord:pics,
                            wechatId:this.ctx.session.wechat.id
                        });
                    }
                    if(choujiang){
                        //没领过红包且中奖了

                        var parseString = require('xml2js').parseString;
                        var request = require('request');
                        var serialize = require('node-serialize');

                        var nonce_str=randomString(32);
                        var sign="";
                        var mch_billno='NWECHATREDORDER'+Date.now();
                        var mch_id="1363799602";
                        var wxappid="wx267f9aa716f2f08b";
                        var send_name=acttivity.name;
                        var re_openid=this.ctx.session.user.openid;
                        var total_amount=Math.floor(Math.random()*(red.max-red.min+1)+red.min)*100;
                        var total_num=1;
                        var wishing=acttivity.wishing;
                        var client_ip="120.76.28.207";
                        var act_name=acttivity.actName;
                        var remark=acttivity.remark;
                        var stringA='act_name='+act_name+'&client_ip='+client_ip+'&mch_billno='+mch_billno+'&mch_id='+mch_id+'&nonce_str='+nonce_str+'&re_openid='+re_openid+'&remark='+remark+'&send_name='+send_name+'&total_amount='+total_amount+'&total_num='+total_num+'&wishing='+wishing+'&wxappid='+wxappid;
                        var stringSignTemp=stringA+"&key=djhuy65AhA9op7A7uA9i7yAGHIK76y50"; //注：key为商户平台设置的密钥key
                        sign=md5(stringSignTemp).toUpperCase(); //注：MD5签名方式
                        // sign=CryptoJS.HmacSHA256(stringSignTemp,'djhuy65AhA9op7A7uA9i7yAGHIK76y50').toString().toUpperCase(); //注：HMAC-SHA256签名方式
                        var data='<xml>';
                        data+='<sign><![CDATA['+sign+']]></sign>';
                        data+='<mch_billno><![CDATA['+mch_billno+']]></mch_billno>';
                        data+='<mch_id><![CDATA['+mch_id+']]></mch_id>';
                        data+='<wxappid><![CDATA['+wxappid+']]></wxappid>';
                        data+='<send_name><![CDATA['+send_name+']]></send_name>';
                        data+='<re_openid><![CDATA['+re_openid+']]></re_openid>';
                        data+='<total_amount><![CDATA['+total_amount+']]></total_amount>';
                        data+='<total_num><![CDATA['+total_num+']]></total_num>';
                        data+='<wishing><![CDATA['+wishing+']]></wishing>';
                        data+='<client_ip><![CDATA['+client_ip+']]></client_ip>';
                        data+='<act_name><![CDATA['+act_name+']]></act_name>';
                        data+='<remark><![CDATA['+remark+']]></remark>';
                        data+='<nonce_str><![CDATA['+nonce_str+']]></nonce_str>';
                        data+='</xml>';
                        var xmlreader = require('xmlreader');  //需要安装 xmlreader包
                        var SEND_REDPACK_URL = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
                        var PFX ='app/public/cert/apiclient_cert.p12';
                        var fs =require('fs');
                        var result = yield new Promise((resolve, reject) => {
                            request({
                                    url: SEND_REDPACK_URL,
                                    method: 'POST',
                                    body: data,
                                    agentOptions: {
                                        pfx: fs.readFileSync(PFX),
                                        passphrase: '1363799602'
                                    }
                                },
                                function(err, response, body){
                                    resolve(body);
                                });
                        });
                        var resultData = yield new Promise((resolve, reject) => {
                            parseString(result, { explicitArray : false, ignoreAttrs : true }, function (err, result) {
                                resolve(result);
                            });
                        });
                        console.log('----------红包发送结果-----------');
                        console.log(resultData.xml.result_code);
                        console.log(resultData.xml.result_msg);
                        console.log('-------------------------------');
                        if(resultData.xml.result_code=='SUCCESS'){
                            yield this.ctx.model.ShopredHistory.create({
                                userId:this.ctx.session.user.id,
                                shopredRedId:redId,
                                amount:total_amount/100,
                                shopredImgId:num,
                                ip:ip,
                                uploadImg:uploadImg
                            });
                            this.ctx.body = {
                                status:true,
                                message:'发放红包成功，请注意微信信息查收！'
                            }
                        }else{
                            yield this.ctx.model.ShopredHistory.create({
                                userId:this.ctx.session.user.id,
                                shopredRedId:redId,
                                amount:-1,
                                shopredImgId:num,
                                remark:resultData.xml.return_msg,
                                ip:ip,
                                uploadImg:uploadImg
                            });
                            this.ctx.body = {
                                status:false,
                                message:'红包发放失败，请联系管理员！'
                            }
                        }
                    }else{
                        yield this.ctx.model.ShopredHistory.create({
                            userId:this.ctx.session.user.id,
                            shopredRedId:redId,
                            amount:0,
                            shopredImgId:num,
                            ip:ip,
                            uploadImg:uploadImg
                        });
                        //没领过红包但没中奖
                        this.ctx.body = {
                            status:true,
                            message:'抱歉没能中奖，赶快去抢下一个！'
                        };
                    }

                }
            }
        }





        // var result =yield this.ctx.curl('https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack', {
        //     method: 'POST',
        //     contentType: 'xml',
        //     data:data,
        // });

    }
    * data(ctx){
        var dataList=yield ctx.model.query("select his.`id`,his.`remark`,users.`id` as userId,users.`status`,users.`nickname`,users.`openid`,his.`amount` as 金额,img.`imgurl` as '图片',his.`ip`,his.`uploadImg`,his.`remark` as '备注',his.`createdAt` as '时间' from `shopred_histories` as his LEFT JOIN `users` ON users.`id`=his.`userId` LEFT JOIN `shopred_imgs` as img ON img.`id`=his.`shopredImgId` ORDER BY his.createdAt DESC LIMIT 60", { type: ctx.model.QueryTypes.SELECT });
        yield ctx.render('shopred/data',{
            dataList:dataList
        });
    }
    * addback(ctx){
     var id=parseInt(ctx.request.body.id);
     var ip=ctx.request.body.ip;
     console.log(ip);
     var inbackIP=yield ctx.model.Backip.findOne({where:{ip:ip}});
     if(!inbackIP){
         yield ctx.model.Backip.create({ip:ip});
     }
     yield ctx.model.User.update({status:1},{where:{id:id}});
     yield ctx.body={
         status:true
     }
    }
  }
  return shopredController;
};
